import express from "express";
import getTimeToData from "../common/getTimeToData.ts";

const consumptionRatioDataDetail = express.Router();
const detailData = async (params: any) => {
    let detailParams = {...params};

    // 如果没有传参默认本月数据
    if (params.timestampRange.length === 0 || Object.keys(params.timestampRange).length === 0) {
        const now = new Date();
        detailParams = {
            timestampRange: [new Date(now.getFullYear(), now.getMonth(), 1), now],
            ignoreFlag: params.ignore,
        };
    }

    // 根据时间获取所有消费表的数据
    const res: any = await getTimeToData("consumptionRecord", detailParams);
    // 创建一个空的对象用于存储统计结果
    const statistics: Record<string, number> = {};

    // 遍历 res 数据
    res.forEach((item: any) => {
        const { tradingType, amount } = item;
        // 如果统计对象中已经有这个 tradingType，就累加金额
        if (statistics[tradingType]) {
            statistics[tradingType] += amount;
        } else {
            // 否则，初始化这个 tradingType 的金额
            statistics[tradingType] = amount;
        }
    });

    // 将统计结果对象转换为数组并按金额降序排序
    const resStatistics = Object.entries(statistics)
        .map(([name, value]) => ({ name, value }))
        .sort((a, b) => b.value - a.value);

    return resStatistics;
};

consumptionRatioDataDetail.post("/consumptionRatio", async (req, res) => {
    try {
        const params = req.body;
        const dataRes: any = await detailData(params); // Wait for the query to complete
        res.send({
            code: 200,
            message: "消费记录接口 请求成功！",
            result: dataRes,
        });
    } catch (error) {
        console.error("Error fetching file records:", error);
        res.status(500).send({
            code: 1,
            message: "消费记录接口 请求失败！",
            result: null,
        });
    }
});

export default consumptionRatioDataDetail;
